/*
 * Copyright (C) 2011 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.moxiu.browser;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.PorterDuff.Mode;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Patterns;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewRootImpl;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.PopupMenu.OnDismissListener;
import android.widget.PopupMenu.OnMenuItemClickListener;

import org.w3c.dom.Text;

import com.moxiu.browser.UrlInputView.StateListener;
import com.moxiu.browser.preferences.BrowserAlcPost;
import com.moxiu.launcher.R;
import com.moxiu.sdk.statistics.MxStatAgent;
//import com.tencent.mm.sdk.platformtools.Log;

public class NavigationBarPhone extends NavigationBarBase implements
        StateListener, OnMenuItemClickListener, OnDismissListener {

    private ImageView mStopButton;
//    private ImageView mMagnify;
//    private ImageView mClearButton;
//    private ImageView mVoiceButton;
    private Drawable mStopDrawable;
    private Drawable mRefreshDrawable;
   // private String mStopDescription;
    //private String mRefreshDescription;
//    private View mTabSwitcher;
//    private View mComboIcon;
    private View mTitleContainer;
//    private View mMore;
    private Drawable mTextfieldBgDrawable;
    private PopupMenu mPopupMenu;
    private boolean mOverflowMenuShowing;
    private boolean mNeedsMenu;
//    private View mIncognitoIcon;
    
    public TextView mTipTv;
    public ImageView searchIcon;
//    private ImageView mTipBt;
    
    
    private final static int STATE_NORMAL = 0;
    private final static int STATE_INPUT = 1;
    private final static int STATE_LOADING = 2;
    
    private int mState = STATE_NORMAL;
    
    private final static int loding = 0;
    private final static int edit = 1;
    private final static int stop = 2;
    private int none=1;
    private int has=2;
    private boolean isgray=false;
    private Resources resources ;
    private int Nstate;
    
    private Drawable forwad,stop_draw,clearstop,Nightclear,search_draw;
    
    public NavigationBarPhone(Context context) {
        super(context);
    }

    public NavigationBarPhone(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public NavigationBarPhone(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        resources = mContext.getResources();
        stop_draw = resources.getDrawable(R.drawable.br_ic_tab_close);
        forwad=resources.getDrawable(R.drawable.br_search_go);
        clearstop=resources.getDrawable(R.drawable.br_search_delete_stop);
        Nightclear=resources.getDrawable(R.drawable.br_nightsearch_delete_stop);
        search_draw=resources.getDrawable(R.drawable.b_m_bd_browser_searchhint_icon);
        mStopButton = (ImageView) findViewById(R.id.stop);
        mStopButton.setVisibility(View.GONE);
//        mTipBt=(ImageView)findViewById(R.id.button);
//        mTipBt.setOnClickListener(this);
        mTipTv = (TextView) findViewById(R.id.tip_tv);
        mTipTv.setOnClickListener(this);
        searchIcon=(ImageView) findViewById(R.id.search_icon);
        searchIcon.setBackgroundDrawable(search_draw);
        searchIcon.setVisibility(View.GONE);
        mStopButton.setOnClickListener(this);
//        mClearButton = (ImageView) findViewById(R.id.clear);
//        mClearButton.setOnClickListener(this);
//        mVoiceButton = (ImageView) findViewById(R.id.voice);
//        mVoiceButton.setOnClickListener(this);
//        mMagnify = (ImageView) findViewById(R.id.magnify);
//        mTabSwitcher = findViewById(R.id.tab_switcher);
//        mTabSwitcher.setOnClickListener(this);
//        mMore = findViewById(R.id.more);
//        mMore.setOnClickListener(this);
//        mComboIcon = findViewById(R.id.iconcombo);
//        mComboIcon.setOnClickListener(this);
        mTitleContainer = findViewById(R.id.title_bg);
        setFocusState(false);
        mStopDrawable = resources.getDrawable(R.drawable.br_search_delete_stop);
        mRefreshDrawable = resources.getDrawable(R.drawable.br_search_refresh);
        //mStopDescription = res.getString(R.string.accessibility_button_stop);
        //mRefreshDescription = res.getString(R.string.accessibility_button_refresh);
//        mTextfieldBgDrawable = res.getDrawable(R.drawable.textfield_active_holo_dark);
        mTextfieldBgDrawable = resources.getDrawable(R.drawable.br_search_input_bg);
        mUrlInput.setContainer(this);
        mUrlInput.setStateListener(this);
        mNeedsMenu = true;// !ViewConfiguration.get(getContext()).hasPermanentMenuKey();
//        mIncognitoIcon = findViewById(R.id.incognito_icon);
    }

    private boolean mIsLoading = false;
    @Override
    public void onProgressStarted() {
        super.onProgressStarted();
        mIsLoading = true;
        setState(STATE_LOADING);
        if (mStopButton.getDrawable() != mStopDrawable) {
            //mStopButton.setImageDrawable(mStopDrawable);
           // mStopButton.setContentDescription(mStopDescription);
            if (mStopButton.getVisibility() != View.VISIBLE) {
//                mComboIcon.setVisibility(View.GONE);
                //mStopButton.setVisibility(View.VISIBLE);
 
            }
        }
    }

    @Override
    public void onProgressStopped() {
        super.onProgressStopped();
        mIsLoading = false;
      //  mStopButton.setImageDrawable(mRefreshDrawable);
      //  mStopButton.setContentDescription(mRefreshDescription);
        if (!isEditingUrl()) {
//            mComboIcon.setVisibility(View.VISIBLE);
        }
        onStateChanged(mUrlInput.getState());
    }

    /**
     * Update the text displayed in the title bar.
     * @param title String to display.  If null, the new tab string will be
     *      shown.
     */
    @Override
    void setDisplayTitle(String title) {
    	try {
    		mUrlInput.setTag(title);
    		if (!isEditingUrl()) {
    			if (title == null || BrowserSettings.getFactoryResetHomeUrl(mContext).equals(title)) {
    				mUrlInput.setText("");// R.string.new_tab);
    			} else {
    				mUrlInput.setText(UrlUtils.stripUrl(title), false);
    			}
    			try {
    				mUrlInput.setSelection(0);
    			} catch (Exception e) {
    				e.printStackTrace();
    			}
    			String txt = mUiController.getCurrentTab().getTitle();
    			if (!TextUtils.isEmpty(txt)) {
    				mUrlInput.setText(txt);
    			}
    		}
    		if(!controller.getHomePage().mHBrowserMainManager.isSearchState){
    			mUrlInput.clearFocus();
    		}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
    }

    @Override
    public void onClick(View v) {
        if (v == mStopButton) {
        	mUrlInput.setText("");
        	mStopButton.setVisibility(View.GONE);
        } else if (v == mTipTv) {
        	
        	mStopButton.setVisibility(View.GONE);
	        if(mTipTv.getText().equals("取消"))	{
	        	if(controller.getHomePage().mHBrowserMainManager.isSearchState){
	        		if(!controller.getHomePage().mHBrowserMainManager.searchisFromHome){
	        			mBaseUi.getActiveTab().hideHomePage();
	        		}else{
	        			controller.getHomePage().mHBrowserMainManager.showHomePageFromOtherTab();
	        		}
	        	}
	        	mStopButton.setVisibility(View.GONE);
	        	if (mTitleBar.isInLoad()) {
	                mUiController.stopLoading();
	            }
	        }else if(mTipTv.getText().equals("刷新")){
	        	WebView web = mBaseUi.getWebView();
	            if (web != null) {
	            	
            		stopEditingUrl();
	                web.reload();
		            DataController.getInstance(mContext).updateVisitedHistory(web.getUrl());
	                MxStatAgent.onEvent("Browser_Page_Refresh_PPC_CY");
	            }
	        }  else{
	        	
	        	mUrlInput.onEditorAction(null, 0, null);
	        }      
        
      
        } else {
            super.onClick(v);
        }
    }
    
    boolean isSearch(String inUrl) {
        String url = UrlUtils.fixUrl(inUrl).trim();
        if (TextUtils.isEmpty(url)) return false;

        if (Patterns.WEB_URL.matcher(url).matches()
                || UrlUtils.ACCEPTED_URI_SCHEMA.matcher(url).matches()) {
            return false;
        }
        return true;
    }

    @Override
    public boolean isMenuShowing() {
        return super.isMenuShowing() || mOverflowMenuShowing;
    }

    void showMenu(View anchor) {
        Activity activity = mUiController.getActivity();
        if (mPopupMenu == null) {
            mPopupMenu = new PopupMenu(mContext, anchor);
            mPopupMenu.setOnMenuItemClickListener(this);
            mPopupMenu.setOnDismissListener(this);
            if (!activity.onCreateOptionsMenu(mPopupMenu.getMenu())) {
                mPopupMenu = null;
                return;
            }
        }
        Menu menu = mPopupMenu.getMenu();
        if (activity.onPrepareOptionsMenu(menu)) {
            mOverflowMenuShowing = true;
            mPopupMenu.show();
        }
    }

    @Override
    public void onDismiss(PopupMenu menu) {
        if (menu == mPopupMenu) {
            onMenuHidden();
        }
    }

    private void onMenuHidden() {
        mOverflowMenuShowing = false;
        mBaseUi.showTitleBarForDuration();
    }

    @Override
    public void onFocusChange(View view, boolean hasFocus) {
        if (view == mUrlInput) {
            if (hasFocus  && !mUrlInput.getText().toString().equals(mUrlInput.getTag())) {
                // only change text if different
            	try {
	            	if((int) ((String) mUrlInput.getTag()).length()==0){
	            		
	            		Tab tab=mUiController.getCurrentTab();
	            		if (tab!=null)
	            		mUrlInput.setText(tab.getUrl());     
	                }/*else{
	                	 mUrlInput.setText((String) mUrlInput.getTag(), false);
	                }*/
	            	  //mUrlInput.setSelectAllOnFocus(true);
	            	//  mUrlInput.selectAll();
            	} catch (IndexOutOfBoundsException e) {
            		// setSpan (0 ... 9) ends beyond length 0
            	}
                
            } else {
                setDisplayTitle(mUrlInput.getText().toString());//xyz
            }
        }
        super.onFocusChange(view, hasFocus);
    }

    private void setState(int state) {
    	if (mIsLoading) {
    		mState = STATE_LOADING;
    	} else {
    		mState = state;
    	}

    	switch (mState) {
		case STATE_NORMAL:		
			if (mStopButton.getDrawable() != mRefreshDrawable) {
	            //mStopButton.setImageDrawable(mRefreshDrawable);
	        }
			break;
		case STATE_LOADING:
		case STATE_INPUT:
			if (mStopButton.getDrawable() != mStopDrawable) {
	            ///mStopButton.setImageDrawable(mStopDrawable);
	        }	
			break;
		default:
			break;
		}
    	
    	
    }
    @Override
    public void onStateChanged(int state) {
//        mVoiceButton.setVisibility(View.GONE);
        switch(state) {
        case StateListener.STATE_NORMAL:
//            mComboIcon.setVisibility(View.VISIBLE);
           // mStopButton.setVisibility(View.VISIBLE);
            setState(STATE_NORMAL);
//            mClearButton.setVisibility(View.GONE);
//            mMagnify.setVisibility(View.GONE);
//            mTabSwitcher.setVisibility(View.VISIBLE);
//            mTitleContainer.setBackgroundDrawable(mTextfieldBgDrawable);
            //new
       //mTitleContainer.setBackgroundColor(getResources().getColor(R.color.br_title_day_textbg));
//            mMore.setVisibility(mNeedsMenu ? View.VISIBLE : View.GONE);
            break;
        case StateListener.STATE_HIGHLIGHTED:
//            mComboIcon.setVisibility(View.GONE);
            //mStopButton.setVisibility(View.VISIBLE);
//            mClearButton.setVisibility(View.GONE);
            if ((mUiController != null) && mUiController.supportsVoice()) {
//                mVoiceButton.setVisibility(View.VISIBLE);
            }
            
            setState(STATE_NORMAL);
            
//            mMagnify.setVisibility(View.GONE);
//            mTabSwitcher.setVisibility(View.GONE);
//            mMore.setVisibility(View.GONE);
           // mTitleContainer.setBackgroundDrawable(mTextfieldBgDrawable);
            break;
        case StateListener.STATE_EDITED:
//            mComboIcon.setVisibility(View.GONE);
           // mStopButton.setVisibility(View.VISIBLE);
            setState(STATE_INPUT);
//            mClearButton.setVisibility(View.VISIBLE);
//            mMagnify.setVisibility(View.VISIBLE);
//            mTabSwitcher.setVisibility(View.GONE);
//            mMore.setVisibility(View.GONE);
           // mTitleContainer.setBackgroundDrawable(mTextfieldBgDrawable);
            break;
        }
        
       
    }

    public TextView getTipTv () {
    	return mTipTv;
    }
//	public ImageView getTipTv () {
//		return mTipBt;
//	}
	public ImageView getStop () {
		return mStopButton;
	}
	
    @Override
    public void onTabDataChanged(Tab tab) {
    	
        super.onTabDataChanged(tab);

//        mIncognitoIcon.setVisibility(tab.isPrivateBrowsingEnabled()
//                ? View.VISIBLE : View.GONE);
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        return mUiController.onOptionsItemSelected(item);
    } 
 /*   @Override
    private void refreshBit(int state){
    	switch (state){
    	case loding:mTipTv.setText("刷新中。。。");
    			 break;
    	case edit:mTipTv.setText("编辑中。。。");
		         break;
    	case stop:mTipTv.setText("暂停中。。。");
		         break;
    	}   		
    }*/

	@Override
	public void refreshBit(int state) {
		Nstate=state;
		switch (state){
    	case loding:
//    		mTipBt.setBackgroundDrawable(stop_draw);
//    		mTipTv.setText("取消");
    		setTipCancel();
    			 break;
    	case edit:
//    		mTipBt.setBackgroundDrawable(forwad);
//    		mTipTv.setText("搜索");
		         break;
    	case stop:
//    		Log.e("DEBUG", "SET REFRESH");
    		setTipRefresh();
//    		mTipBt.setBackgroundDrawable(mRefreshDrawable); 
//    		mTipTv.setText("刷新");
    	 String txt = mUiController.getCurrentTab().getTitle();
         if (TextUtils.isEmpty(txt)) {
             txt = mUiController.getCurrentTab().getUrl();
          }
         mUrlInput.setText(txt);
         break;
    	}  
		super.refreshBit(state);
	}
	
	public void setTipCancel(){
		mTipTv.setVisibility(View.VISIBLE);
		mTipTv.setText("取消");
	}
	
	public void setTipSearch(){
		mTipTv.setVisibility(View.VISIBLE);
		mTipTv.setText("搜索");
	}
	
	public void setTipRefresh(){
		mTipTv.setVisibility(View.VISIBLE);
		mTipTv.setText("刷新");
	}
	

	
	public void setTipGone(){
		mTipTv.setVisibility(View.GONE);
	}
	
	public void setSearchIconGone(){
		searchIcon.setVisibility(View.GONE);
	}
	
	public void setSearchIconVisible(){
		searchIcon.setVisibility(View.VISIBLE);
	}
	
	@Override
	public void setgray(int alpha){
		// mTipBt.setBackgroundColor(color);
		switch (alpha){
		case 1:
//			mTipBt.setAlpha(0.2f);
			mStopButton.setVisibility(View.GONE);
			isgray=true;
			break;
		case 2:
			isgray=false;
			Tab tab=mUiController.getCurrentTab();
			if(tab!=null){
		 	 String txt = mUiController.getCurrentTab().getTitle();
		 	 }
			if(mUrlInput.isgone){
			mStopButton.setVisibility(View.VISIBLE);
			}
//			mTipBt.setAlpha(1.0f);
		}
	
		
		super.setgray(alpha);
	}
	
	public UiController getController(){
		return mUiController;
	}
	
	public void onHomePageShowStateChange(boolean show) {
		if (show) {
//			mTipBt.setVisibility(View.GONE);
//			mTipTv.setVisibility(View.GONE);
		} else {
//			mTipBt.setVisibility(View.VISIBLE);
//			mTipTv.setVisibility(View.VISIBLE);
		}
		setDisplayTitle(mUiController.getCurrentTab()!= null? mUiController.getCurrentTab().getUrl():"");
	}
	
	public void switchToNight(boolean isNight){
		if (isNight) {
        	this.setBackgroundColor(getResources().getColor(R.color.br_night_bg_on));
       /* 	=getDyeDrawable(stop_draw,true);
        	forwad=getDyeDrawable(forwad,true);
        	mRefreshDrawable=getDyeDrawable(mRefreshDrawable,true);*/
        	mStopButton.setImageDrawable(Nightclear);
        	mStopButton.setBackgroundColor(getResources().getColor(R.color.br_night_bg_on)); 
        	search_draw=getDyeDrawable(search_draw,true);
        	if(mTipTv!=null){
        		mTipTv.setTextColor(getResources().getColor(R.color.br_night_text));
        	}
        	mTitleContainer.setBackgroundColor(getResources().getColor(R.color.br_night_bg_on));
        	NightRefresh(Nstate);
        	
		}else {
			this.setBackgroundColor(getResources().getColor(R.color.white));
		/*	stop_draw=getDyeDrawable(stop_draw,false);
			forwad=getDyeDrawable(forwad,false);
			mRefreshDrawable=getDyeDrawable(mRefreshDrawable,false);*/
        	mStopButton.setImageDrawable(clearstop);
        	mStopButton.setBackgroundColor(getResources().getColor(R.color.br_title_day_textbg)); 
        	search_draw=getDyeDrawable(search_draw,true);
        	if(mTipTv!=null){
        		mTipTv.setTextColor(getResources().getColor(R.color.deep_text));
        	}
        	mTitleContainer.setBackgroundDrawable(mTextfieldBgDrawable);
        	NightRefresh(Nstate);
		}
	}


	public  Drawable getDyeDrawable(Drawable drawable,Boolean isNight) {  
		Drawable Ndrawable = drawable;
        try {   
        	if(isNight){        	   	
        		   Ndrawable.setColorFilter(Color.WHITE, Mode.SRC_IN);       	
                }else{
                	Ndrawable.setColorFilter(Color.BLACK, Mode.SRC_IN);	
                }    	                 
        } catch (OutOfMemoryError error) {
        }
		return Ndrawable;
	} 
	
	public void NightRefresh(int state){
		if(mStopButton.getVisibility()==View.VISIBLE){
//			mTipBt.setBackgroundDrawable(forwad);
//			mTipTv.setText("搜索");
		}else{
			switch (state){
	    	case loding:
//	    		mTipBt.setBackgroundDrawable(stop_draw);
//	    		mTipTv.setText("取消");
	    		break;
	    	case edit:
//	    		mTipBt.setBackgroundDrawable(forwad);
//	    		mTipTv.setText("搜索");
			    break;
	    	case stop:
//	    		mTipBt.setBackgroundDrawable(mRefreshDrawable); 
//	    		mTipTv.setText("刷新");
	            break;
	    	}  
		}
	}
	
}
